//
//  DatePickerViewController.swift
//  swift_review
//
//  Created by Andrew on 2024/11/26.
//

import UIKit

class DatePickerViewController: UIViewController {

    private let datePicker: UIDatePicker = {
        let picker = UIDatePicker()
        picker.datePickerMode = .date // 显示年月日时分
        picker.locale = Locale(identifier: "zh_CN") // 设置为中文格式
        picker.calendar = Calendar(identifier: .gregorian) // 使用公历，避免显示周
        picker.timeZone = TimeZone.current // 确保时间准确
//        picker.minimumDate = Date() // 限制最小时间为当前时间
        
        // 根据系统版本设置样式
        if #available(iOS 14.0, *) {
            picker.preferredDatePickerStyle = .wheels // iOS 14+ 使用滚轮样式
        }
        return picker
    }()
        
    private let selectButton: UIButton = {
        let button = UIButton(type: .system)
        button.setTitle("确定", for: .normal)
        button.titleLabel?.font = UIFont.systemFont(ofSize: 18)
        button.addTarget(self, action: #selector(didTapSelectButton), for: .touchUpInside)
        return button
    }()
    
    private let selectedTimeLabel: UILabel = {
        let label = UILabel()
        label.text = "请选择时间"
        label.font = UIFont.systemFont(ofSize: 16)
        label.textAlignment = .center
        label.textColor = .darkGray
        return label
    }()
    
    override func viewDidLoad() {
        super.viewDidLoad()
        setupUI()
    }
    
    private func setupUI() {
        view.backgroundColor = .white
        
        view.addSubview(datePicker)
        view.addSubview(selectButton)
        view.addSubview(selectedTimeLabel)
        
        datePicker.translatesAutoresizingMaskIntoConstraints = false
        selectButton.translatesAutoresizingMaskIntoConstraints = false
        selectedTimeLabel.translatesAutoresizingMaskIntoConstraints = false
        
        NSLayoutConstraint.activate([
            datePicker.centerXAnchor.constraint(equalTo: view.centerXAnchor),
            datePicker.centerYAnchor.constraint(equalTo: view.centerYAnchor, constant: -50),
            
            selectButton.topAnchor.constraint(equalTo: datePicker.bottomAnchor, constant: 20),
            selectButton.centerXAnchor.constraint(equalTo: view.centerXAnchor),
            
            selectedTimeLabel.bottomAnchor.constraint(equalTo: datePicker.topAnchor, constant: -20),
            selectedTimeLabel.centerXAnchor.constraint(equalTo: view.centerXAnchor)
        ])
    }
    
    @objc private func didTapSelectButton() {
        let formatter = DateFormatter()
        formatter.dateFormat = "yyyy-MM-dd HH:mm"
        let selectedTime = formatter.string(from: datePicker.date)
        selectedTimeLabel.text = "选中的时间：\(selectedTime)"
    }
}
